#pragma once
#include <iostream>
#include <string>
#include <vector>

#include <cerrno>
#include <cstring>
#include <strings.h>
#include <cstdlib>

#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

namespace client
{
    using namespace std;
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR
    };
    class udpclient
    {
    public:
        udpclient(const string &serverip, const uint16_t &serverport)
            : _socketfd(-1), _serverip(serverip), _serverport(serverport), _quit(false) {}

        void initclient()
        {
            // 1.创建socket
            _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_socketfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            cout << "client socket success socketfd :" << _socketfd << endl;
            // 2.client需不需要绑定（必须要bind），client需不需要程序员自己绑定？（不需要显示绑定）
            // 由OS自动进行绑定
        }

        // 这个线程只用于接收转发的信息
        static void *sendMessage(void *args)
        {
            int socketfd = *(static_cast<int *>(args));
            pthread_detach(pthread_self());

            while (true)
            {
                char buffer[1024];
                memset(buffer, 0, 1024);
                struct sockaddr_in temp;
                socklen_t temp_len = sizeof(temp);
                size_t n = recvfrom(socketfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&temp, &temp_len);
                if (n > 0)
                    buffer[n] = 0;
                cout << buffer << endl;
            }
            return nullptr;
        }

        void run()
        {
            // 主线程
            pthread_create(&_reader, nullptr, sendMessage, (void *)&_socketfd);

            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(_serverip.c_str());
            server.sin_port = htons(_serverport);

            string message;
            char line[512];
            while (!_quit)
            {
                fprintf(stderr, "please Enter #");
                fflush(stderr);
                // cin >> message;     // ls -a -l会读取到空格
                fgets(line, sizeof(line), stdin);
                message = line;
                message[message.size() - 1] = '\0'; // 去除读取到的换行

                sendto(_socketfd, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
            }
        }

        ~udpclient() {}

    private:
        int _socketfd;        // 打开网络的文件描述符
        string _serverip;     // 发送消息的目的IP
        uint16_t _serverport; // 发送消息的目的端口
        bool _quit;

        pthread_t _reader;
    };
}